/*
        7-8
        编写一个程序，以打印一个文件集合，每个文件从新的一页开始打印，并且打印每个文件相应的标题和页数
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXLEN 100
#define LINE_PAGE 10

void print_page(FILE *fp, char *filename);

int main(int argc, char *argv[])
{
        FILE *fp;
        
        if(argc < 2)
        {
                fprintf(stderr, "error: no file to open\n");
                exit(1);
        }
        else
        {
                for(int i = 1; i < argc; i++)
                {
                        if((fp = fopen(argv[i], "r")) == NULL)
                        {
                                fprintf(stderr, "error: can't open %s\n", argv[i]);
                                exit(1);
                        }
                        print_page(fp, argv[i]);
                        if(ferror(stdout))
                        {
                                fprintf(stderr, "error: writing stdout\n");
                                exit(2);
                        }
                        fclose(fp);
                }
        }
        return 0;
}

void print_page(FILE *fp, char *filename)
{
        char line[MAXLEN];
        int page = 0;
        long lineno = 0;
        int page_start = 1;
        
        while(fgets(line, MAXLEN, fp) != NULL)
        {
                if(page_start)
                {
                        fprintf(stdout, "%40s page %d\n\n", filename, ++page);
                        page_start = 0;
                }
                printf("%s", line);
                lineno++;
                if(lineno % LINE_PAGE == 0)
                {
                        fprintf(stdout, "%80d page\n\f", page);
                        page_start = 1;
                }
        }
        if(lineno % LINE_PAGE != 0)
                fprintf(stdout, "%80d page\n\f", page);
}

